package com.ruoyi.product.listener;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.ruoyi.common.core.constant.MqConstants;
import com.ruoyi.product.domain.WorkOrder;
import com.ruoyi.product.domain.WorkPlan;
import com.ruoyi.product.service.IOrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
public class AddPlanListener {

    @Autowired
    private IOrderService orderService;

    private static final Logger log = LoggerFactory.getLogger(AddPlanListener.class);

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MqConstants.ADD_PLAN_QUEUE,durable = "true"),
            exchange = @Exchange(name = MqConstants.PLAN_EXCHANGE, type = ExchangeTypes.DIRECT),
            key = MqConstants.ADD_PLAN_ROUTING_KEY
    ))
    public void listenAddQueue(String msg){
        WorkPlan workPlan = JSON.parseObject(msg, WorkPlan.class);
        int quantity = workPlan.getQuantity().intValue();
        List<WorkOrder> workOrders = new ArrayList<>();
        for (int i = 0; i < quantity; i++) {
            WorkOrder workOrder = new WorkOrder();
            workOrder.setCellId(workPlan.getCellId());
            workOrder.setCellName(workPlan.getCellName());
            workOrder.setQuantity(new BigDecimal(1));
            workOrder.setMaterialId(workPlan.getMaterialId());
            workOrder.setMaterialName(workPlan.getMaterialName());
            workOrder.setMaterialCode(workPlan.getMaterialCode());
            workOrder.setDelFlag("0");
            workOrder.setWorkOrderCode(IdUtil.getSnowflakeNextId() + "");
            workOrder.setSerialNum(i+1+"");
            workOrder.setPlanCode(workPlan.getPlanCode());
            workOrder.setWorkOrderState(1);
            workOrder.setCreateTime(new Date());
            workOrders.add(workOrder);
        }

        int affect = 0;
        try {
            affect = orderService.addOrderList(workOrders);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("批量根据计划添加订单失败!!");
        }

        if(affect == workOrders.size()){
            log.info("批量根据计划添加订单成功!!");
        }else {
            log.error("批量根据计划添加订单失败!!");
        }
    }
}
